<?php

class User {
	var $debug;
	
	public function __construct($username = false, $password = false) { 
		session_start();
		if($username && $password){
			$this->login($username, $password);
		}
		else {
			if(isset($_SESSION['online'])){
				$this->load_session_data();
			}
			else {			
				$this->debug[] = "user not online";
				//$this->login($username, $password);
			}
		}
	}
	
	public function login($username, $password){
		// do a lookup against the user table inside Eftipi
		global $EFTIPI;
		$this->username = $username;
		$this->password = $password;
		$this->debug[] = "try login for $username : $password";
		
		// does the user exist in eftipi database
		if( isset($EFTIPI->data['users'][$this->username]) ) {
			// does the username and password match
			$data = $EFTIPI->data['users'][$this->username];
			if($data['password'] == $password){
				$this->debug[] = "the user exists and checks out";
				// load the session
				$this->fullname = $data['fullname'];
				$this->uid = $data['uid'];
				$this->save_session_data();
				return true;
			}
			else {
				$this->debug[] = "the user does not check out, bad password";
				return false;
			}
		}
		else {
			$this->debug[] = "couldnt find this user in the database";
			return false;
		}
		
	}
	
	private function load_session_data() {
		$this->username = $_SESSION['username'];
		$this->fullname = $_SESSION['fullname'];
		$this->uid = $_SESSION['uid'];
	}
	
	private function save_session_data() {
		$_SESSION['online'] = true;
		$_SESSION['username'] = $this->username;
		$_SESSION['fullname'] = $this->fullname;
		$_SESSION['uid'] = $this->uid;
	}
	
	public function who_am_i($return = false) {
		$out[] = "<pre>User WHO AM I";
		$out[] = print_r(get_object_vars($this), true);
		$out[] = "</pre>";
		
		if($return){ return implode("\n", $out);}
		else { echo implode("\n", $out); }
	}	
}


?>